<script lang="ts" setup>
import { onMounted, ref } from 'vue';
import { columns } from '@/views/kg/course/utils/columns';
import PureTableBar from '@/components/TableBar/src/bar';
import PureTable from '@pureadmin/table';
import {
  deleteIds,
  onAdd,
  onAssignUsersToCourse,
  onAssignPrerequisitesToCourse,
  onDelete,
  onDeleteBatch,
  onSearch,
  onUpdate,
  courseDialogVisible,
  assignUsersDialogVisible,
  assignPrerequisitesDialogVisible,
  currentCourseId,
  operationType,
} from '@/views/kg/course/utils/hooks';
import Delete from '@iconify-icons/ep/delete';
import EditPen from '@iconify-icons/ep/edit-pen';
import Refresh from '@iconify-icons/ep/refresh';
import { useRenderIcon } from '@/components/CommonIcon/src/hooks';
import AddFill from '@iconify-icons/ri/add-circle-line';
import User from '@iconify-icons/ri/user-line';
import { useCourseStore } from '@/store/kg/course';
import CourseDialog from '@/views/kg/course/course-dialog.vue';
import AssignUsersToCourse from '@/views/kg/course/assign-users-to-course.vue';
import { usePublicHooks } from '@/views/hooks';
import { auth } from '@/views/kg/course/utils/auth';
import { hasAuth } from '@/router/utils';
import Auth from '@/components/Auth/index.vue';
import { selectUserinfo } from '@/components/Table/Userinfo/columns';
import AssignPrerequisitesToCourse from '@/views/kg/course/assign-prerequisites-to-course.vue';

const courseStore = useCourseStore();
const { switchStyle } = usePublicHooks();
const tableRef = ref();
const formRef = ref();
const courseDialogRef = ref();
const assignUsersRef = ref();
const assignPrerequisitesRef = ref();

/** 保存课程用户权限分配 */
const saveCoursePermissions = async () => {
  if (assignUsersRef.value) {
    await courseStore.updateCoursePermissions(currentCourseId.value, assignUsersRef.value.assignUsers);
    assignUsersDialogVisible.value = false;
    await onSearch();
  }
};

/** 保存课程前置课程分配 */
const saveCoursePrerequisites = async () => {
  if (assignPrerequisitesRef.value) {
    await courseStore.updateCoursePrerequisites(currentCourseId.value, assignPrerequisitesRef.value.assignPrerequisites);
    assignPrerequisitesDialogVisible.value = false;
    await onSearch();
  }
};

/**
 * 打开分配用户对话框
 * @param row 课程行数据
 */
const openAssignUsersDialog = (row: any) => {
  // 先设置课程ID，然后打开对话框
  currentCourseId.value = String(row.nodeId);
  assignUsersDialogVisible.value = true;
};

/** 当前页改变时 */
const onCurrentPageChange = async (value: number) => {
  courseStore.pagination.currentPage = value;
  await onSearch();
};

/** 当分页发生变化 */
const onPageSizeChange = async (value: number) => {
  courseStore.pagination.pageSize = value;
  await onSearch();
};

/** 选择多行 */
const onSelectionChange = (rows: Array<any>) => {
  deleteIds.value = rows.map((row: any) => String(row.nodeId));
};

/** 重置表单 */
const resetForm = async () => {
  if (!formRef.value) return;
  formRef.value.resetFields();
  courseStore.resetForm();
  await onSearch();
};

onMounted(() => {
  onSearch();
});
</script>

<template>
  <div class="main">
    <!-- 搜索表单 -->
    <el-form ref="formRef" :inline="true" :model="courseStore.form" class="search-form bg-bg_color w-[99/100] pl-8 pt-[12px] overflow-auto">
      <el-form-item label="课程编码" prop="code">
        <el-input v-model="courseStore.form.code" placeholder="请输入课程编码" class="!w-[180px]" clearable />
      </el-form-item>
      <el-form-item label="课程名称" prop="name">
        <el-input v-model="courseStore.form.name" placeholder="请输入课程名称" class="!w-[180px]" clearable />
      </el-form-item>
      <el-form-item label="课程描述" prop="description">
        <el-input v-model="courseStore.form.description" placeholder="请输入课程描述" class="!w-[180px]" clearable />
      </el-form-item>
      <el-form-item>
        <el-button :icon="useRenderIcon('ri:search-line')" :loading="courseStore.loading" type="primary" @click="onSearch">
          搜索
        </el-button>
        <el-button :icon="useRenderIcon(Refresh)" @click="resetForm">
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <PureTableBar :columns="columns" title="课程管理" @fullscreen="tableRef?.setAdaptive()" @refresh="onSearch">
      <template #buttons>
        <el-button v-if="hasAuth(auth.add)" :icon="useRenderIcon(AddFill)" type="primary" @click="onAdd">
          新增
        </el-button>

        <!-- 批量删除按钮 -->
        <el-button v-if="hasAuth(auth.deleted)" :disabled="!(deleteIds.length > 0)" :icon="useRenderIcon(Delete)" type="danger" @click="onDeleteBatch">
          批量删除
        </el-button>
      </template>

      <template v-slot="{ size, dynamicColumns }">
        <pure-table
          ref="tableRef"
          :adaptiveConfig="{ offsetBottom: 96 }"
          :columns="dynamicColumns"
          :data="courseStore.datalist"
          :header-cell-style="{ background: 'var(--el-fill-color-light)', color: 'var(--el-text-color-primary)' }"
          :loading="courseStore.loading"
          :pagination="courseStore.pagination"
          :size="size"
          adaptive
          align-whole="center"
          border
          highlight-current-row
          row-key="nodeId"
          showOverflowTooltip
          table-layout="auto"
          @page-size-change="onPageSizeChange"
          @selection-change="onSelectionChange"
          @page-current-change="onCurrentPageChange"
        >
          <!-- 创建人插槽 -->
          <template #createUser="{ row }">
            <el-button v-show="row.createdById" link type="primary" @click="selectUserinfo(row.createdById)">
              {{ row.createdByUsername }}
            </el-button>
          </template>

          <!-- 更新人插槽 -->
          <template #updateUser="{ row }">
            <el-button v-show="row.updatedById" link type="primary" @click="selectUserinfo(row.updatedById)">
              {{ row.updatedByUsername }}
            </el-button>
          </template>

          <!-- 操作列 -->
          <template #operation="{ row }">
            <el-button v-if="hasAuth(auth.update)" :icon="useRenderIcon(EditPen)" :size="size" class="reset-margin" link type="primary" @click="onUpdate(row)">
              编辑
            </el-button>
            <el-button v-if="hasAuth(auth.updatePermissions)" :icon="useRenderIcon(User)" :size="size" class="reset-margin" link type="primary" @click="openAssignUsersDialog(row)">
              分配教师
            </el-button>
            <el-button v-if="hasAuth(auth.updatePrerequisites)" :icon="useRenderIcon('ri:list-check')" :size="size" class="reset-margin" link type="primary" @click="onAssignPrerequisitesToCourse(row)">
              前置课程
            </el-button>
            <el-button v-if="hasAuth(auth.deleted)" :icon="useRenderIcon(Delete)" :size="size" class="reset-margin" link type="primary" @click="onDelete(row)">
              删除
            </el-button>
          </template>
        </pure-table>
      </template>
    </PureTableBar>

    <!-- 课程编辑对话框 -->
    <el-dialog
      v-model="courseDialogVisible"
      :destroy-on-close="true"
      :title="operationType === 'add' ? '添加课程' : '编辑课程'"
      width="500px"
    >
      <CourseDialog ref="courseDialogRef" />
      <template #footer>
        <el-button @click="courseDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="courseDialogRef?.onSaveCourse(courseDialogRef.$refs.formRef)">确认</el-button>
      </template>
    </el-dialog>

    <!-- 分配用户对话框 -->
    <el-dialog
      v-model="assignUsersDialogVisible"
      :destroy-on-close="true"
      title="分配教师"
      width="700px"
    >
      <AssignUsersToCourse ref="assignUsersRef" :course-id="currentCourseId" />
      <template #footer>
        <el-button @click="assignUsersDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveCoursePermissions">确认</el-button>
      </template>
    </el-dialog>

    <!-- 添加前置课程对话框 -->
    <el-dialog
      v-model="assignPrerequisitesDialogVisible"
      :destroy-on-close="true"
      title="设置前置课程"
      width="800px"
    >
      <AssignPrerequisitesToCourse ref="assignPrerequisitesRef" :course-id="currentCourseId" />
      <template #footer>
        <el-button @click="assignPrerequisitesDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveCoursePrerequisites">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.main {
  width: 100%;
  height: 100%;
}
</style>
